const { jwtRouter } = require('../../util')
const {query} = require('../../db')
const { do_wxpay } = require('../../pay')

let router = jwtRouter()

router.get('/pay_status/:order_sn', async (req, res, next)=>{
    let order_sn = req.params.order_sn

    let pay_status = await query('SELECT pay_status FROM orders WHERE order_sn = ? AND user_id = ?', [order_sn, req.userId]).catch(next)
    if(pay_status === undefined) return

    if(pay_status.length === 0) {
        res.json({
            'ok': 0,
            'error': '订单不存在！'
        })
        return 
    }

    res.json({
        'ok': 1,
        'data': {
            status: pay_status[0].pay_status
        }
    })
})

router.get('/', async (req, res, next)=>{
    let page = req.query.page || 1
    let pageSize = req.query.page_size || 20
    let pay_status = req.query.pay_status || null

    let offset = (page-1)*pageSize

    let data, total
    if(pay_status === null) {
        data = await query(`SELECT addtime,money,order_sn,pay_status FROM orders WHERE user_id=? LIMIT ${offset},${pageSize}`, req.userId).catch(next)
        if(data === undefined) return

        total = await query('SELECT COUNT(*) total FROM orders WHERE user_id=?', req.userId).catch(next)
        if(total === undefined) return
    } else {
        data = await query(`SELECT addtime,money,order_sn,pay_status FROM orders WHERE user_id=? AND pay_status=? LIMIT ${offset},${pageSize}`, [req.userId, pay_status]).catch(next)
        if(data === undefined) return

        total = await query('SELECT COUNT(*) total FROM orders WHERE user_id=? AND pay_status=?', [req.userId, pay_status]).catch(next)
        if(total === undefined) return
    }

    res.json({
        'ok': 1,
        'total': total[0].total,
        data
    })
})

router.post('/pay', async (req, res, next)=>{
    let order_sn = req.body.order_sn

    let money = await query('SELECT money,pay_status FROM orders WHERE order_sn=? AND user_id=?', [order_sn, req.userId]).catch(next)
    if(money === undefined) return

    if(money.length === 0) {
        res.json({
            'ok': 0,
            'error': '订单不存在！'
        })
        return 
    }

    if(money[0].pay_status === 1) {
        res.json({
            'ok': 0,
            'error': '订单已经支付！'
        })
        return 
    }

    let qrcode = await do_wxpay(order_sn, money[0].money, req.ip)

    res.json({
        'ok': 1,
        'data': {
            order_sn,
            qrcode
        }
    })
})

module.exports = router